package com.allen.flink.batch.sql;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.java.BatchTableEnvironment;
import org.apache.flink.types.Row;

/**
 * 功能: 批Table示例
 *
 * @date: 2020-03-25 15:03
 * @author: Allen
 * @version: 0.0.4-snapshot
 * @Email: allenZyhang@163.com
 * @since: JDK 1.8
 **/
public class BatchTable {
    
    public static void main(String[] args) throws Exception {
        //获取执行环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        
        //创建一个TableEnvironment
        BatchTableEnvironment tabEnv = BatchTableEnvironment.create(env);
        
        //读取数据源
        DataSet<String> ds = env.readTextFile("D:/Flink/user.txt");
        
        //数据转换
        DataSet<Tuple2<String, String>> dsMap = ds.map(new MapFunction<String, Tuple2<String, String>>() {
            @Override
            public Tuple2<String, String> map(final String s) throws Exception {
                String[] arr = s.split(",");
                return new Tuple2<>(arr[0], arr[1]);
            }
        });
        
        //注册为一个表
        Table table =  tabEnv.fromDataSet(dsMap,"uid,name");
    
        Table table2 =table.select("uid,name");
        
        //表转DataSet
        DataSet<Row> ds2 = tabEnv.toDataSet(table2, Row.class);
        
        //打印
        ds2.print();
    }
}
